import React, { useState, useEffect, useReducer, useMemo } from "react";
import {
  Table,
  // Radio,
  Divider,
  Card,
  Input,
  Row,
  Col,
  Space,
  DatePicker,
  Button,
  Modal,
  Form,
  Drawer,
  message,
} from "antd";
import MyIcon from "../../components/Iconfont/Index";
import axios from "axios";
import locale from "antd/es/date-picker/locale/zh_CN";
import { connect } from "react-redux";
import {
  UserOutlined,
  SearchOutlined,
  PlusOutlined,
  RedoOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import moment from "moment";
// const { Search } = Input;
const { RangePicker } = DatePicker;
// const data = {
//   lookeditInfo: false,
// };

function reducer(state, action) {
  let data = { ...state };
  data.lookeditInfo = action.flag;
  return data;
}

const Index = ({ UpateUserInfo }) => {
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [formedit] = Form.useForm();
  // const [selectionType, setSelectionType] = useState("checkbox");
  const [visibleadd, setVisibleadd] = useState(false);
  const [lookeditInfo, setLookEditInfo] = useState(false);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [data, setData] = useState([]);
  const [orderA, setOrderA] = useState(false);
  const [orderB, setOrderB] = useState(false);
  const [state, dispatch] = useReducer(reducer, data);
  const [username, setUsername] = useState("");
  const [timearr, setTimerarr] = useState([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [filterValue, setfilterValue] = useState(null);
  const [form] = Form.useForm();
  const columns = useMemo(() => {
    return [
      {
        title: "序号",
        dataIndex: "xxx",
        render: (text, record, index) => `${(current - 1) * pageSize + index + 1}`,
        align: "center",
      },
      {
        title: "用户名",
        dataIndex: "username",
        align: "center",
      },
      {
        title: "注册地址",
        dataIndex: "registeraddress",
        align: "center",
      },
      {
        title: "注册时间",
        dataIndex: "registertime",
        align: "center",
        render: (text, record, index) =>
          moment.unix(record.registertime).format("YYYY-MM-DD HH:mm:ss"),
        sorter: {
          compare: (a, b) => a.registertime - b.registertime,
          multiple: 2,
        },
        sortOrder: orderA,
      },
      {
        title: "最近一次登录地址",
        dataIndex: "lastloginaddress",
        align: "center",
        render: (text, record, index) =>
          record.lastloginaddress == null ? "暂无最近一次登录地址" : record.lastloginaddress,
      },
      {
        title: "最近一次登录时间",
        dataIndex: "lastlogintime",
        sorter: {
          compare: (a, b) => a.lastlogintime - b.lastlogintime,
          multiple: 2,
        },
        sortOrder: orderB,
        align: "center",
        render: (text, record, index) =>
          record.lastlogintime === 0
            ? "暂无最近一次登录时间"
            : moment.unix(record.lastlogintime).format("YYYY-MM-DD HH:mm:ss"),
      },
      {
        title: "身份",
        dataIndex: "identity",
        filteredValue: filterValue,
        filters: [
          { text: "游客", value: "游客" },
          { text: "管理员", value: "管理员" },
        ],
        align: "center",
      },
      {
        title: "操作",
        dataIndex: "id",
        render: (text, record, index) => (
          <span
            style={{ cursor: "pointer" }}
            onClick={() => {
              formedit.setFieldsValue(record);
              formedit.setFieldsValue({
                registertime: moment.unix(record.registertime).format("YYYY-MM-DD HH:mm:ss"),
                lastloginaddress:
                  record.lastloginaddress == null
                    ? "暂无最近一次登录地址"
                    : record.lastloginaddress,
                lastlogintime:
                  record.lastlogintime === 0
                    ? "暂无最近一次登录时间"
                    : moment.unix(record.lastlogintime).format("YYYY-MM-DD HH:mm:ss"),
              });
              setLookEditInfo((prev) => true);
            }}
          >
            <MyIcon type="icon-see"></MyIcon>&nbsp;查看
          </span>
        ),
        align: "center",
      },
    ];
  });

  const getData = async (
    current,
    pageSize,
    order = "descend",
    order1 = "descend",
    username = "",
    timearr = "",
    identity = ""
  ) => {
    let res= await axios.get("api/alluser", {
      params: {
        current,
        pageSize,
        order: order === undefined || order === "descend" || order === false ? "desc" : "asc",
        order1: order1 === undefined || order1 === "descend" || order === false ? "desc" : "asc",
        timearr: timearr.length === 0 || timearr === undefined ? "" : timearr[0] + " " + timearr[1],
        username,
        identity:
          identity === "" || identity === null || identity.length === 2 ? "" : identity.join(""),
        userid: UpateUserInfo.userInfo.id,
      },
    });
    if (res.data.ok == 0) {
      return message.error(res.data.message);
    }
    // let res = await axios.get("http://rap2.taobao.org:38080/app/mock/253019/showtable");
    console.log(res);
    setData((prev) => res.data.list);
    setTotal((prev) => res.data.total);
  };
  const onChange = (pagination, filters, sorter, extra) => {
    setfilterValue((prev) => filters.identity);
    setLoading((prev) => true);
    setData((prev) => []);
    setPageSize((prev) => pagination.pageSize);
    setCurrent((prev) => pagination.current);
    let sort, sort1;
    if (sorter.length > 0) {
      sort = sorter.filter((item) => item.field === "registertime")[0].order;
      console.log(sort);
      sort1 = sorter.filter((item) => item.field === "lastlogintime")[0].order;
      console.log(sort1);
    } else {
      sort = sorter.field === "registertime" ? sorter.order : undefined;
      sort1 = sorter.field === "lastlogintime" ? sorter.order : undefined;
    }
    setOrderA((prev) => sort);
    setOrderB((prev) => sort1);
    setTimeout(() => {
      getData(
        pagination.current,
        pagination.pageSize,
        sort,
        sort1,
        username,
        timearr,
        filters.identity
      );
      setLoading((prev) => false);
    }, 500);
  };
  const handleOkadd = function () {
    // setVisibleadd((prev) => false);
    form
      .validateFields()
      .then(async (values) => {
        console.log(UpateUserInfo.userInfo);
        if (UpateUserInfo.userInfo.identity !== "管理员") {
          return message.error("您不是管理员,没有权限直接添加用户");
        }
        let { data: res } = await axios.post("api/register", {
          username: values.username,
          password: values.password,
          registeraddress: window.secretip,
          registertime: moment().format("X"),
          userid:UpateUserInfo.userInfo.id
        });
        if (res.ok == -1) {
          return message.error("注册失败");
        } else if (res.ok == 0) {
          return message.error(res.message);
        }
        message.success(res.message);
        form.resetFields();
        setVisibleadd((prev) => false);
        refreshAll();
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const timeOk = function (files) {
    let arr = [];
    if (timearr.length == 2) {
      setTimerarr((prev) => timearr.splice(0, timearr.length));
    }
    console.log(files);
    files.forEach((item) => {
      if (item !== null) {
        arr.push(moment(item._d).unix());
      }
    });

    if (arr.length == 2) {
      setTimerarr((prev) => [...timearr, ...arr]);
    }
  };
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`${selectedRowKeys}`);
      setCheckedKeys((prev) => [...selectedRowKeys]);
    },
    getCheckboxProps: (record) => ({
      //   disabled: record.name === 'Disabled User',
      //   // Column configuration not to be checked
      //   name: record.name,
    }),
  };
  const handleCanceladd = function () {
    form.resetFields();
    setVisibleadd((prev) => false);
  };
  const handleLookEditOk = function () {
    // dispatch({ flag: false });
    setLookEditInfo((prev) => false);
  };
  const handleLookEditCancel = function () {
    // dispatch({ flag: false });
    setLookEditInfo((prev) => false);
  };
  const changename = function (e) {
    e.persist();
    setUsername((prev) => e.target.value);
  };
  const searchUsers = function () {
    console.log(timearr);
    setCurrent((prev) => 1);
    getData(1, pageSize, orderA, orderB, username, timearr);
  };
  const changesedate = function (date) {
    if (!date) {
      setTimerarr((prev) => []);
    }
  };
  const refreshAll = function () {
    setOrderA((prev) => false);
    setOrderB((prev) => false);
    setPageSize((prev) => 5);
    setCurrent((prev) => 1);
    setTimerarr((prev) => []);
    setUsername((prev) => "");
    setfilterValue((prev) => null);
    getData(1, 5, false, false, "", "");
  };
  const isTruePassword = function (rule, value, callback) {
    return new Promise(async (resolve, reject) => {
      if (!value) {
        reject(new Error("确认密码不能为空"));
      } else {
        if (value !== form.getFieldValue("password")) {
          reject(new Error("2次密码不一致"));
        } else {
          resolve();
        }
      }
    });
  };
  const deleteUsers = function () {
    Modal.confirm({
      title: "警告",
      icon: <ExclamationCircleOutlined />,
      content: "确定批量删除用户吗",
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        if (UpateUserInfo.userInfo.identity !== "管理员") {
          return message.error("您不是管理员,没有权限直接添加用户");
        }
        let { data: res } = await axios.get("api/delusers", {
          params: {
            checkedKeys: `${checkedKeys}`,
            userid:UpateUserInfo.userInfo.id
          },
        });
        if (res.ok !== 1) {
          return message.error(res.message);
        }
        message.success(res.message);
        setCurrent((prev) => 1);
        getData(1, pageSize, orderA, orderB, username, timearr, filterValue);
        setCheckedKeys((prev) => []);
      },
    });
  };
  useEffect(() => {
    getData(current, pageSize, orderA, orderB);
  }, []);
  return (
    <div>
      <Card>
        <Row>
          <Col span={6}>
            <Row>
              <Col span={5}>
                <span style={{ fontSize: "20px", lineHeight: "40px" }}>用户名:</span>
              </Col>
              <Col span={12}>
                <Input
                  size="large"
                  placeholder="用户名"
                  onChange={(e) => {
                    changename(e);
                  }}
                  value={username}
                  prefix={<UserOutlined />}
                />
              </Col>
            </Row>
          </Col>
          <Col span={11}>
            <Row>
              <Col span={8}>
                <span style={{ fontSize: "20px", lineHeight: "40px" }}>
                  注册开始的时间到结束时间:
                </span>
              </Col>
              <Col span={15}>
                <RangePicker
                  onChange={changesedate}
                  locale={locale}
                  size="large"
                  showTime
                  onOk={timeOk}
                />
              </Col>
            </Row>
          </Col>
          <Col span={4}>
            <Space size="middle">
              <Button type="primary" size="large" icon={<SearchOutlined />} onClick={searchUsers}>
                搜索
              </Button>
              <Button type="default" size="large" icon={<RedoOutlined />} onClick={refreshAll}>
                重置
              </Button>
            </Space>
          </Col>
          <Col span={3}>
            <Space size="middle">
              <Button
                type="primary"
                size="large"
                onClick={() => {
                  setVisibleadd((prev) => true);
                }}
                icon={<PlusOutlined />}
              >
                新增
              </Button>
              <Button
                type="default"
                size="large"
                disabled={checkedKeys.length === 0}
                icon={<DeleteOutlined />}
                onClick={deleteUsers}
              >
                批量删除
              </Button>
            </Space>
          </Col>
        </Row>
        <Divider />

        <Table
          pagination={{
            showQuickJumper: true,
            pageSizeOptions: ["5", "10", "20", "25"],
            defaultPageSize: 5,
            showSizeChanger: true,
            total: total,
            current: current,
            pageSize: pageSize,
          }}
          locale={{
            cancelSort: "点击取消排序",
            triggerAsc: "点击升序",
            triggerDesc: "点击降序",
          }}
          rowSelection={{
            type: "checkbox",
            ...rowSelection,
          }}
          // loading={true}
          // locale={}
          onChange={onChange}
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={data}
        />
      </Card>
      <Modal
        title="新增用户"
        visible={visibleadd}
        centered
        onOk={handleOkadd}
        onCancel={handleCanceladd}
        okText="添加"
        cancelText="取消"
      >
        <Form colon={false} labelCol={{ span: 4 }} form={form}>
          <Form.Item
            label="用&ensp;戶&ensp;名"
            name="username"
            rules={[
              { required: true, message: "用户名不能为空" },
              { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: "不能有特殊字符" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密&emsp;&emsp;码"
            name="password"
            rules={[
              { required: true, message: "密码不能为空" },
              { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: "不能有特殊字符" },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item label="确认密码" name="isPassword" rules={[{ validator: isTruePassword }]}>
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
      <Drawer
        title="查看并编辑用户（仅作查看,编辑无价值）"
        width={720}
        visible={lookeditInfo}
        onClose={handleLookEditCancel}
        bodyStyle={{ paddingBottom: 80 }}
        footer={
          <div
            style={{
              textAlign: "right",
            }}
          >
            <Button onClick={handleLookEditCancel} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button onClick={handleLookEditOk} type="primary">
              提交
            </Button>
          </div>
        }
      >
        <Form layout="vertical" hideRequiredMark colon={false} form={formedit}>
          <Row gutter={40}>
            <Col span={12}>
              <Form.Item label="用户名" name="username">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="性别" name="sex">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={40}>
            <Col span={12}>
              <Form.Item label="注册IP地址" name="registeraddress">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="注册时间" name="registertime">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={40}>
            <Col span={12}>
              <Form.Item label="注册国家" name="registcountry">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="注册省份" name="registprovince">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={40}>
            <Col span={12}>
              <Form.Item label="注册城市" name="registcity">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="身份" name="identity">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={40}>
            <Col span={12}>
              <Form.Item label="最近一次登录地址" name="lastloginaddress">
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="最近一次登录时间" name="lastlogintime">
                <Input />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Drawer>
    </div>
  );
};

export default connect(
  (state) => state,
  (dispatch) => {
    return {};
  }
)(Index);
